#!/usr/bin/env node

var inquirer = require('inquirer');
var shell = require("shelljs");

if (!shell.which('git')) {
	shell.echo('Sorry, this script requires git');
	shell.exit(1);
	return;
}

var branchType = {
	type: 'list',
	name: 'branchType',
	message: '哪种任务：',
	choices: [
		{
			name: 'bug',
			value: 'fix'
		},
		{
			name: '需求',
			value: 'feat'
		},
		{
			name: '普通',
			value: 'normal'
		}
	]
};

var inputModuleName = {
	type: 'input',
	name: 'moduleName',
	message: '哪个功能或组件？',
	validate: function (input) {
		if (!input) {
			return '不能为空';
		}
		return true;
	}
};

var inputMessage = {
	type: 'input',
	name: 'message',
	message: '处理的问题或者其他描述：',
	validate: function (input) {
		if (!input) {
			return '不能为空';
		}
		return true;
	}
};

function gitCommitMessage({ branchType, moduleName, message }) {
	var exec = require('child_process').exec;
	exec('git status', function (err, stdout, stderr) {
		if (/Changes to be committed/.test(stdout)) {
			const msg = `${branchType}(${moduleName}):${message}`;
			exec(`git commit -m "${msg}"`, function (err, stdout, stderr) {
				if (stdout) {
					console.log(`😁  commit success`);
					console.log(`🥤  with message: ${msg}`);
				} else {
					console.log(err, stderr);
				}
			});
		} else {
			console.log('😂 没有add文件呢？');
		}
	});
}

inquirer
	.prompt([branchType, inputModuleName, inputMessage])
	.then(answers => {
		gitCommitMessage(answers);
	});